<template>
  <!--index.wxml-->
  <view class="container">
    <view v-if="canIUseNicknameComp && !hasUserInfo">
      <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <image class="avatar" :src="userInfo.avatarUrl"></image>
      </button>
      <view class="nickname-wrapper">
        <text class="nickname-label">昵称</text>
        <input type="nickname" class="nickname-input" placeholder="请输入昵称" @change="onInputChange"/>
      </view>
    </view>
    <block v-else-if="!hasUserInfo">
      <button v-if="canIUseGetUserProfile" bindtap="getUserProfile"> 获取头像昵称</button>
      <view v-else> 请使用2.10.4及以上版本基础库</view>
    </block>
    <!-- 	<block v-else>
          <image class="userinfo-avatar" :src="userInfo.avatarUrl" mode="cover"></image>
          <text class="userinfo-nickname">{{userInfo.nickName}}</text>
        </block> -->
    <block class="container" v-else>
      <view class="header-image">
        <image src="../../static/logo.jpg" mode="widthFix" style="height: 40px;"></image>
      </view>
      <view class="header-text">
        <text>家帮办</text>
      </view>
      <view class="moto">尊敬的{{ currentUser.name }}用户，我们将秉承客户至上的理念，采用专业严谨的方法，为您提供优质可靠的服务。</view>
      <view class="bottom" style="text-align: center;">
        <button style="margin-bottom: 20px;" @click="start" type="primary">开始</button>
        <text style="font-size: 24rpx;">本小程序所有计算结果最终解释权归XXXX所有。</text>
      </view>
    </block>

  </view>

</template>

<script>
import {
  mapMutations
} from 'vuex'
import userInfoMixin from "../../common/js/userInfoMixin";

const defaultAvatarUrl =
    'https://7465-test-cloud-5gv55pgtd81284bb-1324061636.tcb.qcloud.la/imgs/default.png?sign=b405486d9a9d169b79c24731e2210ee5&t=1710166985'

export default {
  mixins: [userInfoMixin],
  data() {
    return {
      name: 'index',
      userInfo: {
        avatarUrl: defaultAvatarUrl,
        nickName: ''
      },
      hasUserInfo: false,
      canIUseGetUserProfile: wx.canIUse('getUserProfile'),
      canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    }
  },
  watch: {
    async hasUserInfo(val) {
      if (val) {
        let that = this
        //  调用云函数，获取appid, openid
        wx.cloud.callFunction({
          name: 'user',
          data: {},
          async success(res1) {
            console.log('res1', res1)
            let openid = res1.result.openid

            let db = wx.cloud.database()
            // const users = db.collection('USERS')
            let nickName = that.userInfo.nickName
            await db.collection('USERS').where({
              openid: openid
            }).get({
              async success(res) {
                // res.data 包含该记录的数据
                await uni.setStorage({
                  key: 'currentUser',
                  data: {
                    nickName,
                    openid
                  },
                  async success() {
                    if (res.data.length > 0) {
                      console.log('用户已存在，做覆盖处理')
                      // 修改用户
                      let db = wx.cloud.database()
                      db.collection('USERS').where({
                        openid: openid
                      }).update({
                        data: {
                          name: nickName
                        }
                      }).then(() => {
                        console.log('修改用户成功')
                        // 修改默认的第一个受益人
                        db.collection('JCRS')
                            .where({
                              openid: openid,
                              relation: '本人'
                            }).update({
                          data: {
                            name: nickName
                          }
                        }).then(() => {
                          console.log('修改第一个受益人成功')
                        })
                      })


                    } else {
                      console.log('用户不存在，创建用户')
                      let db = wx.cloud.database()
                      await db.collection('USERS').add({
                        data: {
                          openid: openid,
                          name: nickName
                        }
                      })
                      db = wx.cloud.database()
                      db.collection('JCRS').add({
                        data: {
                          openid: openid,
                          name: nickName,
                          relation: '本人',
                          gender: '',
                          age: ''
                        }
                      }).then(res => {
                        console.log(111, res)
                      })
                    }

                    // 登录后把登陆人的信息存入vuex，供后续使用。
                    that.setCurrentUser({
                      openid: openid,
                      name: nickName,
                      relation: '本人',
                      gender: '',
                      age: ''
                    })
                    console.log(that.currentUser)
                    console.log('写用户成功')
                    console.log('跳转路由')
                  }
                })

              },
              async fail(res2) {
              }
            })
          },
          fail(res) {
            console.log(res)
          }
        })
      }
    },
  },

  async created() {
    this.canIUseGetUserProfile = true
  },
  methods: {
    ...mapMutations(['setCurrentUser']),
    start() {
      this.submitData(null, '100')
    },

    onChooseAvatar(e) {
      const {
        avatarUrl
      } = e.detail
      const {
        nickName
      } = this.userInfo
      this.userInfo.avatarUrl = avatarUrl
      this.hasUserInfo = nickName && avatarUrl && avatarUrl !== defaultAvatarUrl
    },
    onInputChange(e) {
      const nickName = e.detail.value
      const {
        avatarUrl
      } = this.userInfo
      this.userInfo.nickName = nickName
      this.hasUserInfo = nickName && avatarUrl && avatarUrl !== defaultAvatarUrl
    },
    getUserProfile(e) {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res)
          this.userInfo = res.userInfo
          this.hasUserInfo = true
        }
      })
    },
  }
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

.scrollarea {
  flex: 1;
  overflow-y: hidden;
}

.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #aaa;
  width: 80%;
}

.userinfo-avatar {
  overflow: hidden;
  width: 128 rpx;
  height: 128 rpx;
  margin: 20 rpx;
  border-radius: 50%;
}

.usermotto {
  margin-top: 200px;
}

.avatar-wrapper {
  padding: 0;
  width: 56px !important;
  border-radius: 8px;
  margin-top: 40px;
  margin-bottom: 40px;
}

.avatar {
  display: block;
  width: 56px;
  height: 56px;
}

.nickname-wrapper {
  display: flex;
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
  border-top: .5px solid rgba(0, 0, 0, 0.1);
  border-bottom: .5px solid rgba(0, 0, 0, 0.1);
  color: black;
}

.nickname-label {
  width: 105px;
}

.nickname-input {
  flex: 1;
}

.header-image {
  display: flex;
  justify-content: flex-start;
}

.header-text {
  padding: 20px;
  text-align: center;
  font-size: 30px;
  font-weight: 700;
}

.moto {
  font-size: 30 rpx;
}

page {
  height: 100% !important;
}
</style>
